package common

import (
	"github.com/gin-gonic/gin"
	"seven-admin/app/admin/schemas/query"
	"seven-admin/app/admin/schemas/req"
	"seven-admin/app/admin/service/common"
	"seven-admin/app/middleware"
	"seven-admin/core"
	"seven-admin/core/response"
	"seven-admin/util"
)

var DictionariesGroup = core.Group("/common", newDictionariesHandler, regDictionariesMenu, middleware.TokenAuth())

func regDictionariesMenu(rg *gin.RouterGroup, group *core.GroupBase) error {
	return group.Reg(func(handle *dictionariesHandler) {
		rg.GET("/dictionaries/detail", handle.detail)
		rg.GET("/dictionaries/list", handle.list)
		rg.POST("/dictionaries/add", handle.add)
		rg.POST("/dictionaries/edit", handle.edit)
		rg.POST("/dictionaries/del", handle.del)
		rg.GET("/dictionaries/types", handle.types)
		rg.GET("/dictionaries/query", handle.query)
	})
}

type dictionariesHandler struct {
	srv common.DictionariesService
}

func (h *dictionariesHandler) types(c *gin.Context) {
	res, err := h.srv.Types(query.GetAuthReq(c))
	response.CheckAndRespWithData(c, res, err)
}

func (h *dictionariesHandler) query(c *gin.Context) {
	var param req.CommonDictListReq
	if response.IsFailWithResp(c, util.VerifyUtil.VerifyQuery(c, &param)) {
		return
	}
	res, err := h.srv.Query(param, query.GetAuthReq(c))
	response.CheckAndRespWithData(c, res, err)
}

// detail 字典详情
func (hh *dictionariesHandler) detail(c *gin.Context) {
	var detailReq req.IdReq
	if response.IsFailWithResp(c, util.VerifyUtil.VerifyQuery(c, &detailReq)) {
		return
	}
	res, err := hh.srv.Detail(detailReq.ID, query.GetAuthReq(c))
	response.CheckAndRespWithData(c, res, err)
}

// list 字典列表
func (hh *dictionariesHandler) list(c *gin.Context) {
	var page req.PageReq
	var listReq req.CommonDictListReq
	if response.IsFailWithResp(c, util.VerifyUtil.VerifyQuery(c, &page)) {
		return
	}
	if response.IsFailWithResp(c, util.VerifyUtil.VerifyQuery(c, &listReq)) {
		return
	}
	res, err := hh.srv.List(page, listReq, query.GetAuthReq(c))
	response.CheckAndRespWithData(c, res, err)
}

// add 新增字典
func (hh *dictionariesHandler) add(c *gin.Context) {
	var addReq req.CommonDictAddReq
	if response.IsFailWithResp(c, util.VerifyUtil.VerifyJSON(c, &addReq)) {
		return
	}
	err := hh.srv.Add(addReq, query.GetAuthReq(c))
	response.CheckAndResp(c, err)
}

// edit 编辑字典
func (hh *dictionariesHandler) edit(c *gin.Context) {
	var editReq req.CommonDictEditReq
	if response.IsFailWithResp(c, util.VerifyUtil.VerifyJSON(c, &editReq)) {
		return
	}
	err := hh.srv.Edit(editReq, query.GetAuthReq(c))
	response.CheckAndResp(c, err)
}

// del 删除字典
func (hh *dictionariesHandler) del(c *gin.Context) {
	var delReq req.IdReq
	if response.IsFailWithResp(c, util.VerifyUtil.VerifyJSON(c, &delReq)) {
		return
	}
	err := hh.srv.Del(delReq.ID, query.GetAuthReq(c))
	response.CheckAndResp(c, err)
}

func newDictionariesHandler(srv common.DictionariesService) *dictionariesHandler {
	return &dictionariesHandler{srv: srv}
}
